package com.jshoperxms.controller.mall.backstage.member;


import com.jshoperxms.Response;
import com.jshoperxms.controller.mall.backstage.base.BaseTController;
import com.jshoperxms.controller.mall.backstage.base.IBaseCtrl;
import com.jshoperxms.controller.mall.backstage.base.SearchModel;
import com.jshoperxms.controller.utils.BaseTools;
import com.jshoperxms.controller.utils.DateTools;
import com.jshoperxms.controller.utils.SHA1;
import com.jshoperxms.controller.utils.enums.BaseEnums;
import com.jshoperxms.controller.utils.statickey.SerialKeys;
import com.jshoperxms.controller.utils.statickey.StaticKey;
import com.jshoperxms.controller.utils.statickey.TagWords;
import com.jshoperxms.controller.utils.statickey.WarnWrods;
import com.jshoperxms.entity.MemberT;
import com.jshoperxms.service.MemberTService;
import com.jshoperxms.service.impl.Serial;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.monitor.jvm.JvmInfo;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;


@Controller
@RequestMapping("/mall/member")
public class MemberTController extends BaseTController implements IBaseCtrl<MemberT> {
	@Resource
	private MemberTService memberTService;

	//数据形式
	private Map<String, Object> responsedata = new HashMap<>();


	/**
	 *
	 * @api {post} /mall/member/save 添加会员
	 * @apiName  保存会员信息
	 * @apiGroup  MemberService
	 * @apiDescription 后台管理员添加会员
	 * @apiVersion 0.0.1
	 * @apiParam {String} birthday 生日
	 * @apiParam {String} des 描述
	 * @apiParam {String} email 邮件
	 * @apiParam {String} headpath 头像地址
	 * @apiParam {String} loginname 登录名
	 * @apiParam {String} loginpwd 登录密码
	 * @apiParam {String} mobile 手机号码
	 * @apiParam {String} nick 昵称
	 * @apiParam {String} qq QQ
	 * @apiParam {String} realname 真实姓名
	 * @apiParam {String} sex 性别
	 * @apiParam {String} weixin 微信号
	 * @apiParam {String} status 记录状态 启用或者禁用
	 *
	 * @apiSuccess {String} sucflag true标记
	 * @apiSuccess {String} msg  提示信息
	 *
	 * @apiUse operationError
	 * @apiUse operationSuccess
	 *
	 */
	@RequestMapping(value="/save",method= RequestMethod.POST)
	@Override
	public ResponseEntity save(@RequestBody MemberT rq) {
		if(StringUtils.isNotBlank(rq.getLoginname())){
			if(checkDuplicates(rq.getLoginname())){
				MemberT bean=new MemberT();
				bean.setId(this.serial.Serialid(SerialKeys.MEMBER));
				bean.setBelove(0);
				bean.setBirthday(rq.getBirthday());
				bean.setBlood(StaticKey.EMPTY);
				bean.setCity(StaticKey.EMPTY);
				bean.setConstellation(StaticKey.EMPTY);
				bean.setCreatetime(DateTools.getSystemTimeBi());
				bean.setCreatorid(BaseTools.getAdminCreateId());
				bean.setDes(rq.getDes());
				bean.setDistrict(StaticKey.EMPTY);
				bean.setEmail(rq.getEmail());
				bean.setHeadpath(rq.getHeadpath());
				bean.setIntegration(BigDecimal.valueOf(0.0));//累计积分
				bean.setLoginname(rq.getLoginname());
				bean.setLoginpwd(SHA1.getDigestOfString(rq.getLoginpwd()));
				bean.setLoveother(0);
				bean.setMemberGroupId(StaticKey.EMPTY);
				bean.setMemberGroupName(StaticKey.EMPTY);
				bean.setMemberstate(BaseEnums.MemberState.ACTIVE.getState());
				bean.setMerrystatus(BaseEnums.MemberMerryStatus.UNDEFINED.getState());
				bean.setMid(SHA1.getDigestOfString(rq.getId()));//加密的会员id
				bean.setMobile(rq.getMobile());
				bean.setNick(rq.getNick());
				bean.setPostingcount(0);
				bean.setProvince(StaticKey.EMPTY);
				bean.setQq(rq.getQq());
				bean.setRealname(rq.getRealname());
				bean.setSex(rq.getSex());
				bean.setSinaweibo(StaticKey.EMPTY);
				bean.setStatus(rq.getStatus());
				bean.setTag(StaticKey.EMPTY);
				bean.setTelno(StaticKey.EMPTY);
				bean.setUpdatetime(DateTools.getSystemTimeBi());
				bean.setVersiont(1);
				bean.setWeixin(rq.getWeixin());
				bean.setWhichsex(StaticKey.EMPTY);
				memberTService.save(bean);
				responsedata.put(TagWords.SUCCESS, true);
				responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
			}else{
				responsedata.put(TagWords.SUCCESS,false);
				responsedata.put(TagWords.MSG,WarnWrods.ERROR_HAVE_KEY);
			}
		}else{
			responsedata.put(TagWords.SUCCESS,false);
			responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
		}
		return Response.success(responsedata);
	}





	/**
	 *
	 * @api {post} /mall/member/find 查询一条会员记录
	 * @apiName 查询一条的会员记录
	 * @apiGroup  MemberSerivce
	 * @apiDescription 查询一条会员记录
	 * @apiVersion 0.0.1
	 * @apiSuccess {String} sucflag true标记
	 * @apiSuccess {String} msg  提示信息
	 * @apiSuccess {MemberT} bean 数据对象
	 *
	 * @apiUse operationError
	 * @apiUse operationSuccess
	 */
	@RequestMapping(value="/find",method= RequestMethod.POST)
	@Override
	public ResponseEntity find(@RequestBody MemberT rq){
		if(StringUtils.isBlank(rq.getId())){
			responsedata.put(TagWords.SUCCESS,false);
			responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
		}
		MemberT bean=this.memberTService.findByPK(MemberT.class, rq.getId());
		if(bean!=null){
			responsedata.put(TagWords.BEAN,bean);
			responsedata.put(TagWords.SUCCESS,true);
			responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
		}
		return Response.success(responsedata);
	}

	/**
	 *
	 * @api {post} /mall/member/update 更新会员
	 * @apiName   更新会员信息
	 * @apiGroup  MemberService
	 * @apiDescription 后台管理员更新会员
	 * @apiVersion 0.0.1
	 * @apiParam {String} birthday 生日
	 * @apiParam {String} des 描述
	 * @apiParam {String} email 邮件
	 * @apiParam {String} headpath 头像地址
	 * @apiParam {String} loginname 登录名
	 * @apiParam {String} loginpwd 登录密码
	 * @apiParam {String} mobile 手机号码
	 * @apiParam {String} nick 昵称
	 * @apiParam {String} qq QQ
	 * @apiParam {String} realname 真实姓名
	 * @apiParam {String} sex 性别
	 * @apiParam {String} weixin 微信号
	 * @apiParam {String} status 记录状态 启用或者禁用
	 *
	 * @apiSuccess {String} sucflag true标记
	 * @apiSuccess {String} msg  提示信息
	 *
	 * @apiUse operationError
	 * @apiUse operationSuccess
	 *
	 */
	@RequestMapping(value="/update",method= RequestMethod.POST)
	@Override
	public ResponseEntity update(@RequestBody MemberT rq) {
		if(StringUtils.isBlank(rq.getId())){
			responsedata.put(TagWords.SUCCESS,false);
			responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
		}
		MemberT bean=this.memberTService.findByPK(MemberT.class, rq.getId());
		bean.setBirthday(rq.getBirthday());
		bean.setDes(rq.getDes());
		bean.setEmail(rq.getEmail());
		bean.setHeadpath(rq.getHeadpath());
		bean.setMemberstate(rq.getMemberstate());
		bean.setMobile(rq.getMobile());
		bean.setNick(rq.getNick());
		bean.setQq(rq.getQq());
		bean.setRealname(rq.getRealname());
		bean.setSex(rq.getSex());
		bean.setStatus(rq.getStatus());
		bean.setWeixin(rq.getWeixin());
		bean.setUpdatetime(DateTools.getSystemTimeBi());
		bean.setVersiont(bean.getVersiont()+1);
		this.memberTService.update(bean);
		responsedata.put(TagWords.SUCCESS,true);
		responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
		return Response.success(responsedata);
	}

	/**
	 *
	 * @api {post} /mall/member/del 删除会员
	 * @apiName 删除会员
	 * @apiGroup  MemberService
	 * @apiDescription 后台管理员删除会员
	 * @apiVersion 0.0.1
	 * @apiParam {String} 会员id
	 *
	 * @apiSuccess {String} sucflag true标记
	 * @apiSuccess {String} msg  提示信息
	 *
	 * @apiUse operationError
	 * @apiUse operationSuccess
	 */
	@RequestMapping(value="/del",method= RequestMethod.POST)
	@Override
	public ResponseEntity del(@RequestBody MemberT rq) {
		if(StringUtils.isBlank(rq.getId())){
			responsedata.put(TagWords.SUCCESS,false);
			responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
		}
		String ids[]=StringUtils.split(rq.getId(), TagWords.SPLITDOT);
		for(String s:ids){
			MemberT bean=this.memberTService.findByPK(MemberT.class, s);
			if(bean!=null){
				bean.setStatus(BaseEnums.DataUsingState.DEL.getState());
				bean.setUpdatetime(DateTools.getSystemTimeBi());
				this.memberTService.update(bean);
			}
		}
		responsedata.put(TagWords.SUCCESS,true);
		responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
		return Response.success(responsedata);
	}


	@Override
	public ResponseEntity findAll() {
		return null;
	}

	/**
	 *
	 * @api {post} /mall/member/findByPage 查询会员列表
	 * @apiName  查询会员列表
	 * @apiGroup  MemberService
	 * @apiDescription 后台管理员查询会员列表 1，区分是否有排序，是否有搜索，然后进行相应的业务方法调用
	 * @apiVersion 0.0.1
	 * @apiParam {SearchModel} searchModel 搜索模型对象
	 * @apiParam {String} search 快捷搜索对象
	 * @apiParam {String} ordervalue 排序对象
	 * @apiParam {String} ordertype 排序方式
	 *
	 * @apiSuccess {String} sucflag true标记
	 * @apiSuccess {String} msg  提示信息
	 * @apiSuccess {map} data 搜索结果对象
	 *
	 * @apiUse operationError
	 * @apiUse operationSuccess
	 */
	@RequestMapping(value="/findByPage",method= RequestMethod.POST)
	@Override
	public ResponseEntity findByPage(SearchModel searchModel, @RequestParam("search[value]") String search, @RequestParam("order[0][column]") String ordervalue, @RequestParam("order[0][dir]") String ordertype) {
		//检查是否有自定义搜索内容 1标示进行自定义搜索逻辑
		findCustomSearch(searchModel,search,ordervalue,ordertype);
		return Response.success(responsedata);
	}


	/**
	 * 根据自定义搜索内容查询
	 * 1,根据名称搜索
	 * @param searchModel
	 */
	@Override
	public void findCustomSearch(SearchModel searchModel, String search, String ordervalue, String ordertype) {
		//如果有自定义搜索
		if(searchModel.getIsCustomSearch()==1){
			int currentPage=searchModel.getCalCurrentPage();
			int lineSize = searchModel.getLength();
			Criterion criterion;
			Criterion criterion1=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
			Criterion criterion2=null;

			if(StringUtils.isNotBlank(searchModel.getName())){
				criterion2=Restrictions.like("loginname",searchModel.getName(), MatchMode.ANYWHERE);
			}
			if(StringUtils.isNotBlank(search)){
				criterion2=Restrictions.like("loginname",search,MatchMode.ANYWHERE);
			}
			if(criterion2!=null){
				criterion=Restrictions.and(criterion1).add(criterion2);
				int records=this.memberTService.count(MemberT.class,criterion).intValue();
				searchModel.setRecordsTotal(records);
				searchModel.setRecordsFiltered(records);
				responsedata.put(TagWords.RECORDSTOTAL,records);
				responsedata.put(TagWords.RECORDSFILTERED,records);
				List<MemberT> list = this.memberTService.findByCriteriaByPage(
						MemberT.class, criterion,Order.desc(TagWords.UPDATETIME), currentPage,
						lineSize);
				this.processPageList(list);
			}
		}else{
			if(StringUtils.isNotBlank(search)){
				filterSearch(searchModel,search);
			}else{
				findDefaultAll(searchModel,ordervalue,ordertype);
			}
		}
	}

	/**
	 * 根据search[value]过滤查询
	 * @param search
	 */
	@Override
	public void filterSearch(SearchModel searchModel, String search) {
		int currentPage=searchModel.getCalCurrentPage();
		int lineSize = searchModel.getLength();
		Criterion criterion;
		Criterion criterion1=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
		Criterion criterion2=Restrictions.like("loginname",search,MatchMode.ANYWHERE);
		criterion=Restrictions.and(criterion1).add(criterion2);
		int records=this.memberTService.count(MemberT.class,criterion).intValue();
		searchModel.setRecordsTotal(records);
		searchModel.setRecordsFiltered(records);
		responsedata.put(TagWords.RECORDSTOTAL,records);
		responsedata.put(TagWords.RECORDSFILTERED,records);
		List<MemberT> list = this.memberTService.findByCriteriaByPage(
				MemberT.class, criterion,Order.desc(TagWords.UPDATETIME), currentPage,
				lineSize);
		this.processPageList(list);
	}

	/**
	 * 默认查询
	 * @param searchModel
	 */
	@Override
	public void findDefaultAll(SearchModel searchModel, String ordervalue, String ordertype) {
		int currentPage=searchModel.getCalCurrentPage();
		int lineSize = searchModel.getLength();
		Criterion criterion=Restrictions.ne(TagWords.STATUS, BaseEnums.DataUsingState.DEL.getState());
		int records=this.memberTService.count(MemberT.class,criterion).intValue();
		searchModel.setRecordsFiltered(records);
		searchModel.setRecordsTotal(records);
		responsedata.put(TagWords.RECORDSTOTAL,records);
		responsedata.put(TagWords.RECORDSFILTERED,records);
		Order order=Order.desc(TagWords.UPDATETIME);
		if(StringUtils.isNotBlank(ordertype)){
			if(StringUtils.equals(StaticKey.ASC,ordertype)){
				if(StringUtils.equals(ordervalue,StaticKey.TWO)){
					order = Order.asc("loginname");
				}else{
					order=Order.asc(TagWords.UPDATETIME);
				}
			}else{
				if(StringUtils.equals(ordervalue,StaticKey.TWO)){
					order = Order.desc("loginname");
				}else{
					order=Order.desc(TagWords.UPDATETIME);
				}
			}
		}
		List<MemberT> list = this.memberTService.findByCriteriaByPage(
				MemberT.class, criterion,order, currentPage,
				lineSize);
		this.processPageList(list);
	}

	@Override
	public void processPageList(List list) {
		List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
		for (Iterator<MemberT> it = list.iterator(); it.hasNext();) {
			MemberT bean = it.next();
			if(StringUtils.isBlank(bean.getHeadpath())){
				bean.setHeadpath(TagWords.DEFAULTHEAD);
			}
			Map<String, Object> cellMap = new HashMap<String, Object>();
			cellMap.put("id", bean.getId());
			cellMap.put("headpath",bean.getHeadpath());
			cellMap.put("loginname", bean.getLoginname());
			cellMap.put("nick",bean.getNick());
			cellMap.put("sex", BaseEnums.MemberSex.getName(bean.getSex()));
			cellMap.put("mobile",bean.getMobile());
			cellMap.put("status", BaseEnums.DataUsingState.getName(bean.getStatus()));
			cellMap.put("updatetime", DateTools.formateLongDateToString(bean.getUpdatetime().longValue()));
			cellMap.put("version", bean.getVersiont());
			data.add(cellMap);
		}
		responsedata.put(TagWords.DATA,data);
	}

	@Override
	public boolean checkDuplicates(String str) {
		if(StringUtils.isBlank(str)){
			return false;
		}
		Criterion criterion=Restrictions.eq("loginname",str);
		MemberT bean=this.memberTService.findOneByCriteria(MemberT.class, criterion);
		if(bean!=null){
			return false;
		}
		return true;
	}


	/**
	 * 根据会员名称查询会员信息
	 * @param rq
	 * @return
     */
	@RequestMapping(value="/findByMemberName",method= RequestMethod.POST)
	public ResponseEntity findByMemberName(@RequestBody MemberT rq){
		if(StringUtils.isBlank(rq.getLoginname())){
			responsedata.put(TagWords.SUCCESS,false);
			responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
		}
		Criterion criterion=Restrictions.eq("loginname",rq.getLoginname());
		MemberT bean=this.memberTService.findOneByCriteria(MemberT.class,criterion);
		if(bean!=null){
			responsedata.put(TagWords.BEAN,bean);
			responsedata.put(TagWords.SUCCESS,true);
			responsedata.put(TagWords.MSG,TagWords.OPERATION_SUCCESS);
		}
		return Response.success(responsedata);
	}
}
